package com.cz.nongyetongv5.activity;

import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.DaiShangChuanListAdapter;
import com.cz.nongyetongv5.adapter.JiandujianchaListAdapter;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.bean.JianChaDanWei;
import com.cz.nongyetongv5.bean.JianChaHangYe;
import com.cz.nongyetongv5.bean.JianChaNeiRong;
import com.cz.nongyetongv5.bean.JianChaRenYuan;
import com.cz.nongyetongv5.bean.JianDuJianChaRecord;
import com.cz.nongyetongv5.bean.Photo;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.task.UploadDaiShangChuanTask;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.DialogUtil;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.ImageUtil;
import com.cz.nongyetongv5.utils.SerliazableUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class JianDuJianChaUploadActivity_bak extends Fragment implements
        OnClickListener, JiandujianchaListAdapter.onClickItemListener {
    private JiandujianchaListAdapter adapter;
    /**
     * 待上传的ListView
     */
    private ListView lvJianDuJianChaDaiShangChuanList = null;

    /**
     * 数据库工具
     */
    private DatabaseHelper db = null;

    private User user = null;

    private List<JianDuJianChaRecord> jianDuJianChaRecords;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.jiandujiancha_daishangchuan,
                container, false);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initConfig();

    }

    /**
     * 初始化视图
     */
    private void initView() {
        lvJianDuJianChaDaiShangChuanList = (ListView) getActivity()
                .findViewById(R.id.lvJianDuJianChaDaiShangChuanList);

    }

    /**
     * 舒适化数据配置
     */

    private void initConfig() {

        this.db = new DatabaseHelper(getActivity(), CommonConstants.DBNAME,
                null, CommonConstants.DATABASE_VERSION);

        this.user = (User) getActivity().getIntent().getSerializableExtra(
                "user");
        jianDuJianChaRecords = new ArrayList<>();
        reloadData();
    }

    /**
     * 刷新数据
     */
    public void reloadData() {
        jianDuJianChaRecords.addAll(SerliazableUtil
                .getJianDuJianChaRecordByState(1, this.user.getUsername()));
        adapter = new JiandujianchaListAdapter(
                getActivity(), jianDuJianChaRecords);
        lvJianDuJianChaDaiShangChuanList
                .setAdapter(adapter);
        adapter.setOnClickItemListener(this);
    }

    @Override
    public void onClick(View v) {

        if (v instanceof Button) {

            if (v.getId() == R.id.btnDaiShangChuanDelete) {

                if (v.getTag() != null && v.getTag() instanceof Integer) {

                    final int position = (Integer) v.getTag();

                    final CustomDialog deleteDaiShangChuanDialog = new CustomDialog(
                            getActivity());

                    deleteDaiShangChuanDialog
                            .setOnCancleClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    deleteDaiShangChuanDialog.dismiss();
                                }
                            });

                    // 当点击确定的时候
                    deleteDaiShangChuanDialog
                            .setOnActionClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View v) {

                                    DaiShangChuanListAdapter adpJianDuJianChaListAdapter = (DaiShangChuanListAdapter) lvJianDuJianChaDaiShangChuanList
                                            .getAdapter();

                                    if (adpJianDuJianChaListAdapter
                                            .getItem(position) != null
                                            && adpJianDuJianChaListAdapter
                                            .getItem(position) instanceof JianDuJianChaRecord) {

                                        SerliazableUtil
                                                .delete(((JianDuJianChaRecord) adpJianDuJianChaListAdapter
                                                        .getItem(position))
                                                        .getFileId());

                                        // 删除
                                        adpJianDuJianChaListAdapter
                                                .remove(position);

                                        deleteDaiShangChuanDialog.dismiss();

                                        Toast.makeText(getActivity(), "删除成功!",
                                                Toast.LENGTH_SHORT).show();
                                    }

                                }
                            });

                    deleteDaiShangChuanDialog.setMessage(getActivity()
                            .getResources().getString(
                                    R.string.delete_daishangchuan_message));

                    deleteDaiShangChuanDialog.setCancleTxt(getActivity()
                            .getString(R.string.jiandujiancha_item_cancle));

                    deleteDaiShangChuanDialog.setActionTxt(getActivity()
                            .getString(R.string.jiandujiancha_item_sure));

                    deleteDaiShangChuanDialog.show();

                }

            }

            if (v.getId() == R.id.btnDaiShangChuanEdit) {

                final int position = (Integer) v.getTag();

                if (getActivity() instanceof JianDuJianChaMainActivity) {


                    JianDuJianChaMainActivity activity = (JianDuJianChaMainActivity) getActivity();

                    DaiShangChuanListAdapter adpJianDuJianChaListAdapter = (DaiShangChuanListAdapter) lvJianDuJianChaDaiShangChuanList
                            .getAdapter();
                    ((JianDuJianChaRecord) adpJianDuJianChaListAdapter.getItem(position)).setUpload(true);

                    if (adpJianDuJianChaListAdapter.getItem(position) != null
                            && adpJianDuJianChaListAdapter.getItem(position) instanceof JianDuJianChaRecord) {

                        JianDuJianChaRecord record = (JianDuJianChaRecord) adpJianDuJianChaListAdapter
                                .getItem(position);

                        record.setState(1);

                        activity.toEdit(record);

                    }

                }

            }

            if (v.getId() == R.id.btnDaiShangChuanUpload) {

                if (user.isTester()) {

                    DialogUtil.showMessageDialog("演示账户禁止上传..", null,
                            getActivity());

                    return;
                }

                int position = (Integer) v.getTag();

                // 获得每一项的跟布局
                View itemView = lvJianDuJianChaDaiShangChuanList
                        .getChildAt(position - lvJianDuJianChaDaiShangChuanList.getFirstVisiblePosition());

                DaiShangChuanListAdapter adpJianDuJianChaListAdapter = (DaiShangChuanListAdapter) lvJianDuJianChaDaiShangChuanList
                        .getAdapter();

                if (adpJianDuJianChaListAdapter.getItem(position) != null
                        && adpJianDuJianChaListAdapter.getItem(position) instanceof JianDuJianChaRecord) {

                    JianDuJianChaRecord record = (JianDuJianChaRecord) adpJianDuJianChaListAdapter
                            .getItem(position);

                    // 查询到上传的地址
                    String uploadUrl = new ConfigUtil(getResources())
                            .getPreHttpUrl()
                            + getActivity().getResources().getString(
                            R.string.upload_address);

                    // 验证的用户名
                    String authUserName = new ConfigUtil(getResources())
                            .getRestUsername();

                    // 验证的密码
                    String authPassword = new ConfigUtil(getResources())
                            .getRestPassword();

                    // JSON 数据
                    String jsonData = null;

                    // JSON对象
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("add_from", 1);

                        jsonObject.put("add_user", user.getUsername());

                        jsonObject.put("_method", "post");

                        // 开始拼接字符串
                        jsonObject.put("region_code", record.getKnowTown()
                                .getCode());

                        String timeOld = record.getTime();

                        if (!CharsetUtil.isNotNull(timeOld)) {

                            timeOld = new SimpleDateFormat("yyyy-MM-dd")
                                    .format(new Date());

                        }

                        // 进行时间的转换
                        Date oldTimeDate = null;

                        try {
                            oldTimeDate = new SimpleDateFormat("yyyy-MM-dd")
                                    .parse(timeOld);

                        } catch (java.text.ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        String timeNew = new SimpleDateFormat("yyyy-MM-dd")
                                .format(oldTimeDate);

                        jsonObject.put("date", timeNew);

                        // 被检单位合集
                        JSONArray enterpriseJsonObjectArray = new JSONArray();

                        JSONObject enterpriseJsonObject = new JSONObject();

                        enterpriseJsonObject.put("autoCreate", record
                                .getBeiJianDanWei().isCreateShouJianDanWei());

                        enterpriseJsonObject.put("name", record
                                .getBeiJianDanWei().getName());

                        // 不创建并且填写信息的时候
                        if (record.getBeiJianDanWei().isCreateShouJianDanWei()) {
                            enterpriseJsonObject.put("address", record
                                    .getBeiJianDanWei().getAddress());
                            enterpriseJsonObject.put("charge", record
                                    .getBeiJianDanWei().getCharge());
                            enterpriseJsonObject.put("tel", record
                                    .getBeiJianDanWei().getMobile());
                        }

                        enterpriseJsonObjectArray.put(enterpriseJsonObject);

                        jsonObject.put("enterprise", enterpriseJsonObjectArray);

                        // 检查单位合集
                        JSONArray department = new JSONArray();

                        for (JianChaDanWei jcdw : record.getJianChaDanWeis()) {

                            department.put(jcdw.getName());
                        }

                        jsonObject.put("department", department);

                        // 检查人员合集
                        JSONArray inspector = new JSONArray();

                        for (JianChaRenYuan jcry : record.getJianChaReYuans()) {

                            inspector.put(jcry.getName());
                        }

                        jsonObject.put("inspector", inspector);

                        // 检查内容的合集
                        JSONArray category = new JSONArray();

                        for (JianChaNeiRong jcnr : record.getJianChaNeiRongs()) {
                            category.put(jcnr.getId());
                        }

                        jsonObject.put("category", category);
                        // 检查行业的合集
                        JSONArray trade = new JSONArray();

                        for (JianChaHangYe jchy : record.getJianChaHangYes()) {
                            trade.put(jchy.getId());
                        }

                        jsonObject.put("trade", trade);

                        // 产地环境安全
                        JSONObject environment = new JSONObject();

                        if (record.getJianChaJieGuos()[0] != null) {

                            if (record.getJianChaJieGuos()[0].getId() == null) {

                                environment.put("result", 0);

                            } else {
                                environment.put("result",
                                        record.getJianChaJieGuos()[0].getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getJianChaJieGuos()[0].getProblem())) {

                                environment.put("problem", "");

                            } else {

                                environment.put("problem", record
                                        .getJianChaJieGuos()[0].getProblem());
                            }

                        } else {
                            environment.put("result", 0);
                            environment.put("problem", "");

                        }

                        jsonObject.put("environment", environment);

                        // 产地经营的规范性
                        JSONObject operate = new JSONObject();

                        if (record.getJianChaJieGuos()[1] != null) {

                            if (record.getJianChaJieGuos()[1].getId() == null) {
                                operate.put("result", 0);
                            } else {
                                operate.put("result",
                                        record.getJianChaJieGuos()[1].getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getJianChaJieGuos()[1].getProblem())) {

                                operate.put("problem", "");

                            } else {
                                operate.put("problem", record
                                        .getJianChaJieGuos()[1].getProblem());
                            }
                        } else {
                            operate.put("result", 0);
                            operate.put("problem", "");
                        }
                        jsonObject.put("operate", operate);

                        // 产地质量安全性
                        JSONObject quality = new JSONObject();

                        if (record.getJianChaJieGuos()[2] != null) {

                            if (record.getJianChaJieGuos()[2].getId() == null) {
                                quality.put("result", 0);
                            } else {

                                quality.put("result",
                                        record.getJianChaJieGuos()[2].getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getJianChaJieGuos()[2].getProblem())) {

                                quality.put("problem", "");

                            } else {

                                quality.put("problem", record
                                        .getJianChaJieGuos()[2].getProblem());
                            }

                        } else {
                            quality.put("result", 0);
                            quality.put("problem", "");

                        }

                        jsonObject.put("quality", quality);

                        // 产地包装合法性
                        JSONObject mark = new JSONObject();

                        if (record.getJianChaJieGuos()[3] != null) {

                            if (record.getJianChaJieGuos()[3].getId() == null) {
                                mark.put("result", 0);
                            } else {

                                mark.put("result",
                                        record.getJianChaJieGuos()[3].getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getJianChaJieGuos()[3].getProblem())) {

                                mark.put("problem", "");

                            } else {
                                mark.put("problem",
                                        record.getJianChaJieGuos()[3]
                                                .getProblem());
                            }

                        } else {
                            mark.put("result", 0);
                            mark.put("problem", "");

                        }

                        jsonObject.put("mark", mark);

                        // 其他
                        JSONObject other = new JSONObject();

                        if (record.getJianChaJieGuos()[4] != null) {

                            if (record.getJianChaJieGuos()[4].getId() == null) {
                                other.put("result", 0);
                            } else {

                                other.put("result",
                                        record.getJianChaJieGuos()[4].getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getJianChaJieGuos()[4].getProblem())) {

                                other.put("problem", "");

                            } else {

                                other.put("problem",
                                        record.getJianChaJieGuos()[4]
                                                .getProblem());
                            }

                        } else {
                            other.put("result", 0);
                            other.put("problem", "");

                        }

                        jsonObject.put("other", other);

                        // 日常监管
                        JSONObject inspection = new JSONObject();

                        if (record.getRiChangJianGuan() != null) {

                            if (record.getRiChangJianGuan().getId() == null) {
                                inspection.put("result", 0);
                            } else {

                                inspection.put("result", record
                                        .getRiChangJianGuan().getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getRiChangJianGuan().getProblem())) {

                                inspection.put("problem", "");

                            } else {

                                inspection.put("problem", record
                                        .getRiChangJianGuan().getProblem());
                            }

                            if (!CharsetUtil.isNotNull(record.getJianChaJiLu())) {

                                inspection.put("content", "");

                            } else {

                                inspection.put("content",
                                        record.getJianChaJiLu());
                            }

                        } else {

                            if (!CharsetUtil.isNotNull(record.getJianChaJiLu())) {

                                inspection.put("content", "");

                            } else {

                                inspection.put("content",
                                        record.getJianChaJiLu());
                            }
                            inspection.put("result", 0);
                            inspection.put("problem", "");
                        }
                        jsonObject.put("inspection", inspection);
                        JSONObject measure = new JSONObject();

                        if (CharsetUtil.isNotNull(record.getZhengGaiYiJian())) {

                            measure.put("opinion", record.getZhengGaiYiJian());

                        } else {
                            measure.put("opinion", "");
                        }

                        measure.put("content", "");
                        measure.put("result", "");
                        measure.put("date", "");

                        jsonObject.put("measure", measure);

                        jsonObject.put("add_sign", ImageUtil
                                .bitToBase64FromFile(record.getQianMingPath()));

                        JSONArray photos = new JSONArray();
                        for (Photo photo : record.getUploadPhoto()) {
                            JSONObject photoJsonObj = new JSONObject();
                            photoJsonObj.put("base64", ImageUtil
                                    .bitToBase64FromFile(photo
                                            .getBigPhotoPath()));
                            photoJsonObj.put("comment", photo.getComment());
                            photoJsonObj.put("time", photo.getPhotoTime());
                            photoJsonObj.put("position", photo.getAddressDesc());
                            photoJsonObj.put("longitude", photo.getLongitude());
                            photoJsonObj.put("latitude", photo.getLatitude());
                            photos.put(photoJsonObj);
                        }
                        jsonObject.put("photo", photos);
                        jsonData = jsonObject.toString();
                        //                        System.out.println(jsonData);
                    } catch (JSONException e) {
                        jsonData = null;
                    } catch (ParseException e) {
                        jsonData = null;
                    }
                    // 启动任务
                    UploadDaiShangChuanTask task = new UploadDaiShangChuanTask(
                            itemView,
                            getActivity(),
                            record,
                            (DaiShangChuanListAdapter) lvJianDuJianChaDaiShangChuanList
                                    .getAdapter(), uploadUrl, jsonData,
                            authUserName, authPassword,null);
                    //                                        执行任务
                    task.execute();
                }
            }

        }
    }

    @Override
    public void onClickItemListener(final int position, View v) {
        switch (v.getId()) {
            case R.id.btnDaiShangChuanDelete:
                final CustomDialog deleteDaiShangChuanDialog = new CustomDialog(
                        getActivity());

                deleteDaiShangChuanDialog
                        .setOnCancleClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                deleteDaiShangChuanDialog.dismiss();
                            }
                        });

                // 当点击确定的时候
                deleteDaiShangChuanDialog
                        .setOnActionClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                SerliazableUtil
                                        .delete((jianDuJianChaRecords.get(position))
                                                .getFileId());
                                // 删除
                                jianDuJianChaRecords.remove(position);
                                deleteDaiShangChuanDialog.dismiss();
                                adapter.notifyDataSetChanged();
                                Toast.makeText(getActivity(), "删除成功!",
                                        Toast.LENGTH_SHORT).show();

                            }
                        });

                deleteDaiShangChuanDialog.setMessage(getActivity()
                        .getResources().getString(
                                R.string.delete_daishangchuan_message));

                deleteDaiShangChuanDialog.setCancleTxt(getActivity()
                        .getString(R.string.jiandujiancha_item_cancle));

                deleteDaiShangChuanDialog.setActionTxt(getActivity()
                        .getString(R.string.jiandujiancha_item_sure));

                deleteDaiShangChuanDialog.show();
                break;
            case R.id.btnDaiShangChuanEdit:
                JianDuJianChaRecord record1 = jianDuJianChaRecords.get(position);
                record1.setState(1);
                ((JianDuJianChaMainActivity) getActivity()).toEdit(record1);
                break;
            case R.id.btnDaiShangChuanUpload:
                if (user.isTester()) {

                    DialogUtil.showMessageDialog("演示账户禁止上传..", null,
                            getActivity());

                    return;
                }
                JianDuJianChaRecord record = jianDuJianChaRecords.get(position);
                // 查询到上传的地址
                String uploadUrl = new ConfigUtil(getResources())
                        .getPreHttpUrl()
                        + getActivity().getResources().getString(
                        R.string.upload_address);

                // 验证的用户名
                String authUserName = new ConfigUtil(getResources())
                        .getRestUsername();

                // 验证的密码
                String authPassword = new ConfigUtil(getResources())
                        .getRestPassword();

                // JSON 数据
                String jsonData = null;

                // JSON对象
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("add_from", 1);

                    jsonObject.put("add_user", user.getUsername());

                    jsonObject.put("_method", "post");

                    // 开始拼接字符串
                    jsonObject.put("region_code", record.getKnowTown()
                            .getCode());

                    String timeOld = record.getTime();

                    if (!CharsetUtil.isNotNull(timeOld)) {

                        timeOld = new SimpleDateFormat("yyyy-MM-dd")
                                .format(new Date());

                    }

                    // 进行时间的转换
                    Date oldTimeDate = null;

                    try {
                        oldTimeDate = new SimpleDateFormat("yyyy-MM-dd")
                                .parse(timeOld);

                    } catch (java.text.ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    String timeNew = new SimpleDateFormat("yyyy-MM-dd")
                            .format(oldTimeDate);

                    jsonObject.put("date", timeNew);

                    // 被检单位合集
                    JSONArray enterpriseJsonObjectArray = new JSONArray();

                    JSONObject enterpriseJsonObject = new JSONObject();

                    enterpriseJsonObject.put("autoCreate", record
                            .getBeiJianDanWei().isCreateShouJianDanWei());

                    enterpriseJsonObject.put("name", record
                            .getBeiJianDanWei().getName());

                    // 不创建并且填写信息的时候
                    if (record.getBeiJianDanWei().isCreateShouJianDanWei()) {
                        enterpriseJsonObject.put("address", record
                                .getBeiJianDanWei().getAddress());
                        enterpriseJsonObject.put("charge", record
                                .getBeiJianDanWei().getCharge());
                        enterpriseJsonObject.put("tel", record
                                .getBeiJianDanWei().getMobile());
                    }

                    enterpriseJsonObjectArray.put(enterpriseJsonObject);

                    jsonObject.put("enterprise", enterpriseJsonObjectArray);

                    // 检查单位合集
                    JSONArray department = new JSONArray();

                    for (JianChaDanWei jcdw : record.getJianChaDanWeis()) {

                        department.put(jcdw.getName());
                    }

                    jsonObject.put("department", department);

                    // 检查人员合集
                    JSONArray inspector = new JSONArray();

                    for (JianChaRenYuan jcry : record.getJianChaReYuans()) {

                        inspector.put(jcry.getName());
                    }

                    jsonObject.put("inspector", inspector);

                    // 检查内容的合集
                    JSONArray category = new JSONArray();

                    for (JianChaNeiRong jcnr : record.getJianChaNeiRongs()) {
                        category.put(jcnr.getId());
                    }

                    jsonObject.put("category", category);
                    // 检查行业的合集
                    JSONArray trade = new JSONArray();

                    for (JianChaHangYe jchy : record.getJianChaHangYes()) {
                        trade.put(jchy.getId());
                    }

                    jsonObject.put("trade", trade);

                    // 产地环境安全
                    JSONObject environment = new JSONObject();

                    if (record.getJianChaJieGuos()[0] != null) {

                        if (record.getJianChaJieGuos()[0].getId() == null) {

                            environment.put("result", 0);

                        } else {
                            environment.put("result",
                                    record.getJianChaJieGuos()[0].getId());
                        }

                        if (!CharsetUtil.isNotNull(record
                                .getJianChaJieGuos()[0].getProblem())) {

                            environment.put("problem", "");

                        } else {

                            environment.put("problem", record
                                    .getJianChaJieGuos()[0].getProblem());
                        }

                    } else {
                        environment.put("result", 0);
                        environment.put("problem", "");

                    }

                    jsonObject.put("environment", environment);

                    // 产地经营的规范性
                    JSONObject operate = new JSONObject();

                    if (record.getJianChaJieGuos()[1] != null) {

                        if (record.getJianChaJieGuos()[1].getId() == null) {
                            operate.put("result", 0);
                        } else {
                            operate.put("result",
                                    record.getJianChaJieGuos()[1].getId());
                        }

                        if (!CharsetUtil.isNotNull(record
                                .getJianChaJieGuos()[1].getProblem())) {

                            operate.put("problem", "");

                        } else {
                            operate.put("problem", record
                                    .getJianChaJieGuos()[1].getProblem());
                        }
                    } else {
                        operate.put("result", 0);
                        operate.put("problem", "");
                    }
                    jsonObject.put("operate", operate);

                    // 产地质量安全性
                    JSONObject quality = new JSONObject();

                    if (record.getJianChaJieGuos()[2] != null) {

                        if (record.getJianChaJieGuos()[2].getId() == null) {
                            quality.put("result", 0);
                        } else {

                            quality.put("result",
                                    record.getJianChaJieGuos()[2].getId());
                        }

                        if (!CharsetUtil.isNotNull(record
                                .getJianChaJieGuos()[2].getProblem())) {

                            quality.put("problem", "");

                        } else {

                            quality.put("problem", record
                                    .getJianChaJieGuos()[2].getProblem());
                        }

                    } else {
                        quality.put("result", 0);
                        quality.put("problem", "");

                    }

                    jsonObject.put("quality", quality);

                    // 产地包装合法性
                    JSONObject mark = new JSONObject();

                    if (record.getJianChaJieGuos()[3] != null) {

                        if (record.getJianChaJieGuos()[3].getId() == null) {
                            mark.put("result", 0);
                        } else {

                            mark.put("result",
                                    record.getJianChaJieGuos()[3].getId());
                        }

                        if (!CharsetUtil.isNotNull(record
                                .getJianChaJieGuos()[3].getProblem())) {

                            mark.put("problem", "");

                        } else {
                            mark.put("problem",
                                    record.getJianChaJieGuos()[3]
                                            .getProblem());
                        }

                    } else {
                        mark.put("result", 0);
                        mark.put("problem", "");

                    }

                    jsonObject.put("mark", mark);

                    // 其他
                    JSONObject other = new JSONObject();

                    if (record.getJianChaJieGuos()[4] != null) {

                        if (record.getJianChaJieGuos()[4].getId() == null) {
                            other.put("result", 0);
                        } else {

                            other.put("result",
                                    record.getJianChaJieGuos()[4].getId());
                        }

                        if (!CharsetUtil.isNotNull(record
                                .getJianChaJieGuos()[4].getProblem())) {

                            other.put("problem", "");

                        } else {

                            other.put("problem",
                                    record.getJianChaJieGuos()[4]
                                            .getProblem());
                        }

                    } else {
                        other.put("result", 0);
                        other.put("problem", "");

                    }

                    jsonObject.put("other", other);

                    // 日常监管
                    JSONObject inspection = new JSONObject();

                    if (record.getRiChangJianGuan() != null) {

                        if (record.getRiChangJianGuan().getId() == null) {
                            inspection.put("result", 0);
                        } else {

                            inspection.put("result", record
                                    .getRiChangJianGuan().getId());
                        }

                        if (!CharsetUtil.isNotNull(record
                                .getRiChangJianGuan().getProblem())) {

                            inspection.put("problem", "");

                        } else {

                            inspection.put("problem", record
                                    .getRiChangJianGuan().getProblem());
                        }

                        if (!CharsetUtil.isNotNull(record.getJianChaJiLu())) {

                            inspection.put("content", "");

                        } else {

                            inspection.put("content",
                                    record.getJianChaJiLu());
                        }

                    } else {

                        if (!CharsetUtil.isNotNull(record.getJianChaJiLu())) {

                            inspection.put("content", "");

                        } else {

                            inspection.put("content",
                                    record.getJianChaJiLu());
                        }
                        inspection.put("result", 0);
                        inspection.put("problem", "");
                    }
                    jsonObject.put("inspection", inspection);
                    JSONObject measure = new JSONObject();

                    if (CharsetUtil.isNotNull(record.getZhengGaiYiJian())) {

                        measure.put("opinion", record.getZhengGaiYiJian());

                    } else {
                        measure.put("opinion", "");
                    }

                    measure.put("content", "");
                    measure.put("result", "");
                    measure.put("date", "");

                    jsonObject.put("measure", measure);

                    jsonObject.put("add_sign", ImageUtil
                            .bitToBase64FromFile(record.getQianMingPath()));

                    JSONArray photos = new JSONArray();
                    for (Photo photo : record.getUploadPhoto()) {
                        JSONObject photoJsonObj = new JSONObject();
                        photoJsonObj.put("base64", ImageUtil
                                .bitToBase64FromFile(photo
                                        .getBigPhotoPath()));
                        photoJsonObj.put("comment", photo.getComment());
                        photoJsonObj.put("time", photo.getPhotoTime());
                        photoJsonObj.put("position", photo.getAddressDesc());
                        photoJsonObj.put("longitude", photo.getLongitude());
                        photoJsonObj.put("latitude", photo.getLatitude());
                        photos.put(photoJsonObj);
                    }
                    jsonObject.put("photo", photos);
                    jsonData = jsonObject.toString();
                    //                        System.out.println(jsonData);
                } catch (JSONException e) {
                    jsonData = null;
                } catch (ParseException e) {
                    jsonData = null;
                }
                jianDuJianChaRecords.get(position).setUpload(true);
                jianDuJianChaRecords.get(position).setBack(false);
                adapter.notifyDataSetChanged();


                // 启动任务
                JiandujianchaUploadTask task = new JiandujianchaUploadTask(position, uploadUrl, jsonData,
                        authUserName, authPassword);
                //                UploadDaiShangChuanTask task = new UploadDaiShangChuanTask(
                //                        itemView,
                //                        getActivity(),
                //                        record,
                //                        (DaiShangChuanListAdapter) lvJianDuJianChaDaiShangChuanList
                //                                .getAdapter(), uploadUrl, jsonData,
                //                        authUserName, authPassword);
                //                //                                        执行任务
                task.execute();
                break;
            case R.id.btnBackUploadMenu:
                jianDuJianChaRecords.get(position).setBack(true);
                adapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }


    class JiandujianchaUploadTask extends
            AsyncTask<Integer, Integer, String> {

        private String jsonData = null;

        private String authUserName = null;

        private String authPassword = null;

        private String requestUrl = null;

        /**
         * 请求返回的结果
         */


        /**
         * 返回的结果
         */
        private int responseCode;

        private String responseBody;

        private int pos;

        /**
         * 判断请求是否返回数据
         */
        private boolean executeFinish = false;

        public JiandujianchaUploadTask(int position, String requestUrl,
                                       String jsonData, String authUserName, String authPassword) {
            this.requestUrl = requestUrl;
            this.jsonData = jsonData;
            this.authUserName = authUserName;
            this.authPassword = authPassword;
            this.pos = position;

        }

        /**
         * 在 doInBackground 之前
         */
        @Override
        protected void onPreExecute() {
        }

        /**
         * 在后台执行的逻辑
         */
        @Override
        protected String doInBackground(Integer... params) {
            int startProgress = (int) (50 * Math.random() + 50);
            publishProgress(startProgress);

            // http 访问
            final HttpUtils httpUtil = HttpUtils.getInstance();

            httpUtil.setOnRequestExecuted(new HttpUtils.OnRequestExecuted()

            {

                @Override
                public void onRequestExecuted(int responseCode, String responseBody) {
                    JiandujianchaUploadTask.this.responseBody = responseBody;
                    JiandujianchaUploadTask.this.responseCode = responseCode;

                    try {
                        JSONObject jsonObject = new JSONObject(responseBody);

                        if (jsonObject.isNull("status")) {

                            JiandujianchaUploadTask.this.responseCode = HttpUtils.UNKNOWERROR;

                        } else {

                            String state = jsonObject.getString("status");

                            if (!"success".equals(state) && !"true".equals(state)
                                    && !"1".equals(state)) {

                                JiandujianchaUploadTask.this.responseCode = HttpUtils.UNKNOWERROR;

                            }

                        }

                    } catch (JSONException e) {

                        JiandujianchaUploadTask.this.responseCode = HttpUtils.UNKNOWERROR;
                    }

                }
            });

            httpUtil.sendRequest(requestUrl, jsonData, "POST", "UTF-8",
                    authUserName, authPassword, null);

            //		int currentProgress = tpUploadProgress.getProgress();
            //
            //		if (currentProgress >= 100) {
            //			tpUploadProgress.setText("服务器正在处理...");
            //		}

            return null;
        }

        // 当执行完成后
        @Override
        protected void onPostExecute(String result) {

            executeFinish = true;
            if (responseCode != HttpUtils.SUCCESS) {
                //			btnBackUploadMenu.setVisibility(View.VISIBLE);

                // 当返回按钮点击的时候显示主菜单
                //			btnBackUploadMenu.setOnClickListener(new OnClickListener() {
                //
                //				@Override
                //				public void onClick(View v) {
                //
                //					v.setVisibility(View.GONE);
                //
                //					llMenuLayout.setVisibility(View.VISIBLE);
                //
                //					llProgressLayout.setVisibility(View.GONE);
                //
                //				}
                //			});

            }

            switch (responseCode) {
                case HttpUtils.SUCCESS:
                    jianDuJianChaRecords.get(pos).setProgress(100);
                    jianDuJianChaRecords.remove(pos);
                    String id = jianDuJianChaRecords.get(pos).getFileId();
                    SerliazableUtil.delete(id);
                    adapter.notifyDataSetChanged();
                    Toast.makeText(getActivity(), "上传成功", Toast.LENGTH_LONG).show();
                    break;
                case HttpUtils.TIMEOUT:
                    jianDuJianChaRecords.get(pos).setMsg(getActivity().getResources().getString(
                            R.string.message_socktimeout));
                    Toast.makeText(getActivity(), getActivity().getResources().getString(
                            R.string.message_socktimeout), Toast.LENGTH_LONG).show();
                    break;
                case HttpUtils.NETWORK_ERR:
                    jianDuJianChaRecords.get(pos).setMsg(getActivity().getResources().getString(
                            R.string.error_no_network));
                    Toast.makeText(getActivity(), getActivity().getResources().getString(
                            R.string.error_no_network), Toast.LENGTH_LONG).show();
                    break;
                case HttpUtils.UNKNOWERROR:
                    jianDuJianChaRecords.get(pos).setMsg(getActivity().getResources().getString(
                            R.string.message_softerror));
                    Toast.makeText(getActivity(), getActivity().getResources().getString(
                            R.string.message_softerror), Toast.LENGTH_LONG).show();
                    break;
            }
        }

        /**
         * 当进度更新的时候
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

            int progress = values[0];
            //        System.out.println(progress);
            //            if (jianDuJianChaRecords.get(pos).getProgress() < 100) {
            //                handler.postDelayed(new Runnable() {
            //                    @Override
            //                    public void run() {
            //                        jianDuJianChaRecords.get(pos).setProgress(jianDuJianChaRecords.get(pos).getProgress() + 1);
            //                        adapter.notifyDataSetChanged();
            //                    }
            //                }, 1000);
            //            }

            jianDuJianChaRecords.get(pos).setProgress(progress);
            adapter.notifyDataSetChanged();
            //       	tpUploadProgress.setProgress(progress);
            //
            //		tpUploadProgress.startRandomProgress();

        }

    }

}
